package com.ayz.gateway.center.infrastructure.config;


import com.ayz.gateway.center.domain.repository.IApiRepository;
import com.ayz.gateway.center.domain.repository.IGatewayServiceRepository;
import com.ayz.gateway.center.infrastructure.application.GatewayCenterStartListener;
import com.ayz.gateway.center.infrastructure.remoting.GatewayCenterService;
import com.ayz.gateway.center.infrastructure.remoting.config.GatewayCenterConfig;
import com.ayz.gateway.center.infrastructure.remoting.defaults.DefaultGatewayCenterService;
import com.ayz.gateway.server.grpc.GrpcRemotingServer;
import com.ayz.gateway.server.grpc.GrpcServerConfig;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @ClassName GatewayCenterServiceConfig
 * @Description TODO: 网关注册中心服务端配置类
 * @Author 快乐的星球
 * @Date 2023/5/23 21:51
 * @Version 1.0
 **/
@Configuration(
        proxyBeanMethods = false
)
@Getter
public class GatewayCenterServiceConfig {

    @Value("${gateway.remoting.server}")
    private Integer remotingServerPort;

    @Value("${nginx.container.name}")
    private String ngxContainerName;
    @Bean
    @ConditionalOnMissingBean
    public GrpcRemotingServer grpcRemotingServer(){
        //1:GRPC服务端的配置
        GrpcServerConfig grpcServerConfig=new GrpcServerConfig();
        if(remotingServerPort!=null){
            grpcServerConfig.setListenPort(remotingServerPort);
        }
        //2:构建RemotingServer
        return new GrpcRemotingServer(grpcServerConfig);
    }
    @Bean
    @ConditionalOnMissingBean
    public GatewayCenterService gatewayCenterService(GrpcRemotingServer grpcRemotingServer, IApiRepository apiRepository, IGatewayServiceRepository gatewayServiceRepository){
        //1:创建网关注册中心配置参数类
        GatewayCenterConfig gatewayCenterConfig=new GatewayCenterConfig();
        //2:创建网关注册中心服务类
        GatewayCenterService gatewayCenterService=new DefaultGatewayCenterService(gatewayCenterConfig,grpcRemotingServer,apiRepository,gatewayServiceRepository);
        gatewayCenterService.start();
        return gatewayCenterService;
    }

    @Bean
    @ConditionalOnMissingBean
    public GatewayCenterStartListener gatewayCenterStartListener(){
        return new GatewayCenterStartListener(getNgxContainerName());
    }
}
